<?php
/**
 * 体检预约
 *
 * User: kaikaic
 * Date: 2018/10/28
 * Time: 21:10
 */

namespace app\api\controller;

use app\api\service\MainService;
use app\exam\service\MecService;
use app\exam\service\MecSetService;
use app\api\model\OrderModel;
use app\exam\service\OrderService;
use controller\BasicApi;
use service\ConfigService;
use service\WechatService;
use think\Db;

class Book extends BasicApi {
    /**
     * 首页
     */
    public function index() {
        $accountID = intval($this->getParams("uid"));           // 用户ID
        $mecID = intval($this->getParams("mec_id"));            // 体检中心ID
        $setID = $this->getParams("set_id");            // 套餐ID
        $examDate = $this->getParams("exam_date");              // 体检日期
        $enterpriseID = intval($this->getParams("e_id", "0"));  // 企业ID
        $euid = intval($this->getParams("euid",0));  // ID
        $price= intval($this->getParams("price",0));  // ID
        $name = $this->getParams("name",'');
        $card_no =    $this->getParams("card_no",'');
        $groupid = intval($this->getParams("groupid",0));  // ID
        if (!$accountID || !$mecID || !$setID || !$examDate ) {
            $this->error("参数错误", 0);
        }

        $type = intval($this->getParams("type",1));                                 // 个人or团体
        $typeArr = array(1, 2);
        if (!in_array($type, $typeArr)) {
            $type = 1;
        }
        if ($type == 2) {
            if (!$enterpriseID) {
                $this->error("参数错误", 0);
            }
            if (!$groupid) {
                $this->error("参数错误", 0);
            }

        }

        if (!$this->isDate($examDate)) {
            $this->error("体检日期格式错误", 0);
        }

        $mec = MecService::getInstance()->getMec($mecID);
        if (!$mec) {
            $this->error("没有这个体检中心", 0);
        }
        $setID = substr($setID,0,strlen($setID)-1);
        $setArr = explode(",",$setID);
        for ($i=0;$i<count($setArr);$i++){
            $set = MecSetService::getInstance()->getSet($setArr[$i]);
            if (!$set) {
                $this->error("没有这个套餐", 0);
            }
            if ($set['mec_id'] != $mecID) {
                $this->error("没有这个套餐", 0);
            }
        }
        // 订单是否存在


        $params = array();
        if($euid){
            $examuserinfo = MainService::findMember($euid);

            $params['exam_name'] = $examuserinfo['name'];
            $params['exam_idCard'] = $examuserinfo['card_no'];
        }else{
            $params['exam_name'] = $name;
            $params['exam_idCard'] = $card_no;
            $params['group_id'] = $groupid;

        }
        $params['account_id'] = $accountID;
        $params['mec_id'] = $mecID;
        $params['set_id'] = $setID;
        $params['exam_date'] = $examDate;
        $params['price'] = $price;
        $orderModel = new OrderModel();
        $flag = $orderModel->isOrderExist($params);
        if ($flag) {
            $this->error("已经有当天的预约", 0);
        }

        $params['type'] = $type;
        if ($type == 2) {
            $params['enterprise_id'] = $enterpriseID;
            $params['order_status'] = 2;
            $params['pay_status'] = 2;
        }else{
            $params['order_status'] = 1;
            $params['pay_status'] = 1;
        }
        $params['create_time'] = time();

        $result = $orderModel->createOrder($params);



        if ($result) {
            $res = $orderModel->orderInfo($result);
            $res = MainService::getOrderInfoByOrdersn($res['order_sn']);
//            $msg['account_id']  = $res['account_id'];
//            $msg['type']  = 1;
//            $msg['title']  = '恭喜你，预约订单成功';
//            $msg['content']  = '<p>您的体检预约：</p>'.
//                '<p>订单号:'.$res['order_sn'].'</p>'.
//                '<p>体检中心:'.$res['mec']['name'].'</p>'.
//                '<p>体检套餐:'.$res['setname'].'</p>'.
//                '<p>体检时间:'.$res['exam_date'].'</p>'.
//                '<p> 预约成功,请尽快支付</p>'.
//                '<p> 地址:'.$res['mec']['address'].'</p>';
//            $msg['create_time']  = time();
//            $msg['isnew']  = 1;
//            Db::name('exam_mesage')->insert($msg);
            $this->success('预约成功',$res);
        }else {
            $this->error("预约失败, 稍候重试", 0);
        }

    }

    private function isDate($data) {
        if (date("Y-m-d", strtotime($data)) == $data) {
            return true;
        }else {
            return false;
        }
    }

    private function getParams($param, $default="") {
//        return $this->request->post($param, $default);
        return $this->request->get($param, $default);
    }

    /*
    * 订单 - 微信支付
    * http://fri.game.com/index/order/wxpay?order_sn=460580141610194198&openId=oyWmc0p5tE7JHDlfN29xVT5sAyOM
    */
    public function wxpay()
    {
        $orderSN = $this->request->param('order_sn', 0);
        $openId = $this->request->param('openId', 0);
        $request = $this->request;
        $ip_address = $request->ip();
        $notifyurl = "https://".$_SERVER['HTTP_HOST']."/api/book/wxnotify";
        if ($orderSN && $openId) {
        } else {
            $this->error('非法操作！');
        }
        $orderInfo = MainService::getOrderInfoByOrdersn($orderSN);
        if($orderInfo['exam_date'] < date('Y-m-d')){
            $this->error('该订单体检时间已过期！');
        }
        elseif ($orderInfo['pay_status'] != 1) {
            $this->error('订单已支付！');
        } else {
            $return = WechatService::unifiedorder($openId, $orderSN, '湘上健康', $orderInfo['price'], $ip_address,$notifyurl);
            if (isset($return['return_code']) && $return['return_code'] == 'SUCCESS') {
                 $this->success('获取成功！', $return);
            } else {
                 $this->error('签名返还错误！', $return);
            }
        }
    }

    // 微信支付回调
    public function wxnotify()
    {

        $filename = "aa.txt";
        $fp = fopen($filename, 'a+');
        fwrite($fp, "success");
        $receipt = $_REQUEST;
        if ($receipt == null) {
            $receipt = file_get_contents("php://input");
            if ($receipt == null) {
                $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
            }
        }
        $receipt = WechatService::xmlToArray($receipt);
//        $flag = WechatService::checkSign($receipt);
//        $flag = 1;
//        $receipt =   array (
//            'appid' => 'wxa66f8506c1e54be6',
//            'attach' => 'EXAM20181129102650000000003601',
//            'bank_type' => 'CFT',
//            'cash_fee' => '1',
//            'fee_type' => 'CNY',
//            'is_subscribe' => 'N',
//            'mch_id' => '1518554421',
//            'nonce_str' => 'xs26pzjk06a4287v99strbq4ho1jtpb8',
//            'openid' => 'oS0JW45eNqq9Yb0DT0DmGU6H8VCg',
//            'out_trade_no' => 'EXAM20181129102650000000003601',
//            'result_code' => 'SUCCESS',
//            'return_code' => 'SUCCESS',
//            'sign' => '3C8CAB3FAC4EC38BF926D0C8994716E7',
//            'time_end' => '20181129103349',
//            'total_fee' => '1',
//            'trade_type' => 'JSAPI',
//            'transaction_id' => '4200000218201811298399776014',
//        );
        $flag = WechatService::checkSign($receipt);
        if ($flag) {
            fwrite($fp, var_export($receipt, true));
            // 支付日志
            $res =   $order =  MainService::getOrderInfoByOrdersn($receipt['out_trade_no']);
            $msg['account_id']  = $res['account_id'];
            $msg['type']  = 1;
            $msg['title']  = '恭喜你，预约订单支付成功';
            $msg['content']  = '<p>您的体检预约：</p>'.
                '<p>订单号:'.$res['order_sn'].'</p>'.
                '<p>体检中心:'.$res['mec']['name'].'</p>'.
                '<p>体检套餐:'.$res['setname'].'</p>'.
                '<p>体检时间:'.$res['exam_date'].'</p>'.
                '<p> 预约成功,请9点之前达到</p>'.
                '<p> 地址:'.$res['mec']['address'].'</p>';
            $msg['create_time']  = time();
            $msg['isnew']  = 1;
            $res = Db::name('exam_mesage')->insert($msg);
            $logData['account_id'] = $order['account_id'];
            $logData['order_sn'] = $receipt['out_trade_no'];
            $logData['create_time'] = time();
            $logData['money'] = $receipt['total_fee'] / 100;
            $logData['transaction_id'] = $receipt['transaction_id'];
            $pay_id = Db::name("wechat_pay_notify")->insertGetId($logData);
            // 订单表状态
            $data['pay_status'] = 2;
            $data['order_status'] = 1;
            $data['update_time'] = time();
            $ups = Db::name("exam_order")->where("order_sn", $receipt['out_trade_no'])->update($data);

            // 支付状态
            $pay_s = Db::name("exam_order_pay")->where("pay_sn", $res['pay_sn'])->update(array('api_pay_state'=>1));

            // 向第三方下单
//            $money =  $receipt['total_fee']/100;
//            $thirdData = array(
//                'orderId' => $order['order_sn'],
//                'pdtId' => $order_ticket['third_code'],
//                'num' => $order_ticket['num'],
//                'contactor' => $order_ticket['name'],
//                'cellphone' => $order_ticket['mobile'],
//                'money' => $money
//            );
//            $third = OrderService::createOrderThird($thirdData);
//            $fp = fopen($filename, 'a+');
//            fwrite($fp, "success3");
////            fwrite($fp, var_export($thirdData, true));
//            fclose($fp);
//            if ($third) {
//                Db::name("scenic_order_pay")->where("pay_sn", $receipt['out_trade_no'])->update(array('api_pay_code'=>$third['qrCode'],"api_pay_orderid"=>$third['orderId']));
//                $data['status_order'] = 3;
//                $ups = Db::name("ScenicOrder")->where("pay_sn", $receipt['out_trade_no'])->update($data);
                exit('SUCCESS');
//            } else {
//                exit('SUCCESS');
//            }
        }
    }
    public function getorderlist(){
        $page = $this->request->param('page',1)-1;
        $size = 6;
        $order_status = $this->request->param('order_status',0);
        $account_id = $this->request->param('uid');
        $orderList = MainService::getOrderList($account_id,$order_status,$page,$size);
        $this->success( '获取成功',$orderList);
    }
    public function cancelorder(){
        $orderSN = $this->request->param('order_sn', 0);

        $orderInfo = MainService::getOrderInfoByOrdersn($orderSN);
        if ($orderInfo['order_status'] != 1) {
            $this->error('该订单不能取消');
        } else {
            $update['order_status'] = 10;
            $update['cancel_time'] = time();
            $staus =  MainService::cancelOrder($orderSN,$update);
            if($staus){
               $this->success('取消成功');
            }else{
               $this->error('取消失败');
            }
        }
    }
    public function orderdetail(){
        $orderSN = $this->request->param('order_sn', 0);

        $orderInfo = MainService::getOrderInfoByOrdersn($orderSN);
        if ($orderInfo) {
            $this->success('获取成功',$orderInfo);
        } else {
            $this->error('参数错误');
        }
    }
    public function changedate(){
        $ordersn = $this->request->param('order_sn', 0);
        $data['exam_date'] = $exam_date = $this->request->param('exam_date', 0);
        $data['update_time'] = time();
        $orderInfo = Db::name("exam_order")->where('order_sn',$ordersn)->update($data);
        if ($orderInfo) {
            $res['status'] = 2;
           Db::name("exam_group_member")->where('order_sn',$ordersn)->update($res);
            $this->success('预约成功',$orderInfo);
        } else {
            $this->error('参数错误');
        }
    }

}

